<?php
/**
 * 
 * @author Kai
 * @version 1.01 (05.07.2011)
 * 
 */
class CUserAuth
{    
	/**
	 * Method for logging in
	 * @param $username
	 * @param $password
	 */
	static public function login($username, $password) 
	{
		// If a user is already logged in: refuse the request
		if(CUserAuth::isLoggedIn() == false) 
		{
			// Convert password into sha1-hash
			$password = md5($password);
	
			// Fetching the user record
			$sql = CSingleton::get("sql::sql");
			$qry = $sql->prepare("SELECT * FROM Mitarbeiter WHERE benutzername = ? AND passwd = ? AND inBearbeitung = 0 AND status <> 6 AND status <> 2");
			$qry->execute(array($username, $password));
			
			// Check if the login was successful
			if($qry->rowCount() == 1) 
			{
				// Fetch ID
				$user = $qry->fetch(PDO::FETCH_ASSOC);
				
				// Set session-flag
				$_SESSION['isLoggedIn'] = true;
				$_SESSION['userID'] = $user['idMitarbeiter'];
				$_SESSION['vorname'] = $user['vorname'];
				$_SESSION['name'] = $user['name'];
				$_SESSION['benutzername'] = $user['benutzername'];
				$_SESSION['rechteID'] = $user['rechte'];
				$_SESSION['gstelleId'] = $user['gstelleId'];
                                $_SESSION['status'] = $user['status'];
                                $_SESSION['pw_ablauf'] = $user['passwd_datum'];
				
				// ...login successful
				return true;
			} 
			// ...login failed
			else 
			{
				return false;
			}
		}
		
		// ...already logged in 
		return false;
	}
	
	/**
	 * Static method for logging out
	 */
	static public function logout()
	{
		// Delete all data from $_SESSION
		$_SESSION = array(); 
		
		// If session cookie exists... 
		if (ini_get("session.use_cookies")) {
		    $params = session_get_cookie_params();
		    
		    // ... remove it
		    setcookie(session_name(), '', time() - 42000, $params["path"],
		        $params["domain"], $params["secure"], $params["httponly"]
		    );
		}
		
		// Destroy the session
		session_destroy();	
	}
        
        /**
        * Enter description here ...
        */
        public static function genPasswordExpireDate()
        {
            // Now + 30 Tage
            $time = strtotime("+30 day");
            return date("Y-m-d", $time);
        }
	
	
	/**
	 * Returns true if a user-session exists
	 */
	static public function isLoggedIn()
	{
		if($_SESSION['isLoggedIn']==true) 
			return true;
		else 
			return false;
	}
	
	/**
	 * Check if password has expired
	 * 
	 * Date format
	 * YYYY-MM-DD
	 */
	static public function passwdExpired()
	{
		// Check if the user password has expired
		if(CUserAuth::isLoggedIn() == true) 
		{	
			// Fetching the user record
			$sql = CSingleton::get("sql::sql");
			$qry = $sql->prepare("SELECT passwd_datum FROM Mitarbeiter WHERE idMitarbeiter = ?");
			$qry->execute(array($_SESSION['userID']));
			
			if($qry->rowCount() == 1) 
			{
				// Fetch expire-date
				$user = $qry->fetch(PDO::FETCH_ASSOC);
				$date = date("Y-m-d", time());
				
				// 2012-01-01 >= 2011-11-11 [true]
				if($date >= $user['passwd_datum']) 
				{
				    $sql->exec("UPDATE Mitarbeiter SET status = '4' WHERE idMitarbeiter = " . $_SESSION['userID']);
				    CUserAuth::logout();
				    return true;
				}
			} 
		}
		return false;	    
	}
        
        static public function getPasswordExpireDays()
        {
            $tNow = time();
            $tExpireDate = strtotime($_SESSION['pw_ablauf']);
            $tDiff = $tExpireDate - $tNow;
            
            // Auf Tage umrechnen
            $days = $tDiff / (60 * 60 * 24);
            
            // Aufrunden
            $days = ceil($days);
            
            return $days;
        }
	
	
	/**
	 * 
	 * Checks for a certain status
	 * @param unknown_type $statusID
	 */
	static public function accessDenied()
	{
	    header("LOCATION: index.php?page=access-denied");  
	}
	
	static public function hasAccess($statusID)
	{
            
            if($statusID == 1 && $_SESSION['rechteID'] > 1) {
                CUserAuth::accessDenied();
            }
            
            if($statusID == 2 && $_SESSION['rechteID'] < 2) {
                CUserAuth::accessDenied();
            }

            if($statusID == 3 && $_SESSION['rechteID'] < 3) {
                CUserAuth::accessDenied();
            }
            
            if($statusID == 4 && $_SESSION['rechteID'] < 4) {
                CUserAuth::accessDenied();
            }
            //-----
            if($statusID == 5 && ($_SESSION['rechteID'] < 5  || $_SESSION['rechteID'] > 7)) { //nur recht 5, 6 und 7
                CUserAuth::accessDenied();
            }
            
            if($statusID == 6 && ($_SESSION['rechteID'] < 6  || $_SESSION['rechteID'] > 7)) {//nur recht 6 und 7
                CUserAuth::accessDenied();
            }
            
            if($statusID == 7 && $_SESSION['rechteID'] != 7) {//nur recht 7
                CUserAuth::accessDenied();
            }
                
	}
	
	static public function isAdmin()
	{
            // ADMIN
            if($_SESSION['rechteID'] != 1) {
                CUserAuth::accessDenied();
            }	 
	}
        
        static public function checkPassword($pw1, $pw2, $uid)
        {
            $error = array();
            if($pw1 != $pw2) {
               $error[] = "Passw&ouml;rter nicht identisch!";
               return $error;
            }
            
            $sql = CSingleton::get("sql::sql");
            $qry = $sql->prepare("SELECT passwd FROM Mitarbeiter WHERE idMitarbeiter = ?");
            $qry->execute(array($uid));
            $m = $qry->fetch(PDO::FETCH_ASSOC);
            
            if($m['passwd'] == md5($pw1)) {
                $error[] = "Passwort ist mit altem Passwort identisch!";
                return $error;
            }
            
            $upper_letters = range('A','Z');
            $special_chars = array('#','&','@','$','_','%','?','+', '!', '§', '/', '(', ')', '=');
            
            $is_uc_char = false;
            $is_special_char = false;
            for($i=0; $i<strlen($pw1); $i++)
            {
                if(in_array( $pw1[$i], $upper_letters )) $is_uc_char = true;
                if(in_array( $pw1[$i], $special_chars )) $is_special_char = true;
            }
            
            if($is_uc_char == false) $error[] = "Passwort enth&auml;lt keinen Gro&szlig;buchstaben!";
            if($is_special_char == false) $error[] = "Passwort enth&auml;lt kein Sonderzeichen!";
            
            if(strlen($pw1) > 8) $error[] = "Passwort enth&auml;lt mehr als 8 Zeichen!";
            if(strlen($pw1) < 8) $error[] = "Passwort enth&auml;lt weniger als 8 Zeichen!";
            
            if(count($error) > 0) return $error; else return true;
        }
	
}
?>